// MultiWave2Mp3.cpp : Defines the entry point for the console application.
//

#include "MultiWave2Mp3.h"
#include <stdio.h>
#include <tchar.h>

#include <list>

using namespace std;


list<PROCESS_INFORMATION> processes;


DWORD MW2MP3_CreateProcess(LPTSTR inputWave, LPTSTR outputMp3) {
	
	wchar_t sCmdLine[4096];


	// cmd: wav2mp3.exe input.wav output.mp3
	_stprintf_s(sCmdLine, 4096, L"wav2mp3.exe %s %s", inputWave, outputMp3);

	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	ZeroMemory( &pi, sizeof(pi) );


	BOOL success = CreateProcess( NULL,   // No module name (use command line)
        sCmdLine,        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi );           // Pointer to PROCESS_INFORMATION structure

	processes.push_back(pi);

	return pi.dwProcessId;
}

bool MW2MP3_HasMoreProcesses() {
	return !processes.empty();
}

void MW2MP3_CheckProcesses(MW2MP3CALLBACKFUNCTION callBackFunc) {
	DWORD exitCode;

	list<PROCESS_INFORMATION>::iterator iter;

	iter = processes.begin();
	while( iter != processes.end() ) {

		PROCESS_INFORMATION pi = *iter;
		GetExitCodeProcess(pi.hProcess, &exitCode);
		if ( exitCode != STILL_ACTIVE ) {
			callBackFunc(pi.dwProcessId, exitCode);
			iter = processes.erase(iter);
		} else {
			iter++;
		}
	}
}


/* Remove this as the iterator conflicts with CheckProcesses()'s iterator
void MW2MP3_RemoveProcess(DWORD dwProcessId) {
	list<PROCESS_INFORMATION>::iterator iter;
	for(iter = processes.begin(); iter!= processes.end(); iter++) {
		PROCESS_INFORMATION pi = *iter;
		if ( pi.dwProcessId == dwProcessId ) {
			processes.erase( iter );
			return;
		}
	}
}
*/


void MW2MP3_TerminateProcesses() {

	list<PROCESS_INFORMATION>::iterator iter;
	for(iter = processes.begin(); iter!= processes.end(); iter++) {
		PROCESS_INFORMATION pi = *iter;
		TerminateProcess(pi.hProcess, 0);
		CloseHandle(pi.hProcess);
	}

	processes.clear();

}

